package org.kazuhiko.rpg.client;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.kazuhiko.rpg.client.net.RPGSession;
import org.kazuhiko.rpg.client.net.SessionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Client
{
	//The logger
	private static final Logger logger = LoggerFactory.getLogger( Client.class );
	
	//Singleton way
	private static Client instance;
	
	private final IoConnector connector = new NioSocketConnector();
	
	private String serverAddress;
	
	private int port;
	
	private ConnectFuture future;
	
	public Client() throws IOException
	{
		logger.info( "Starting client..." );
		
		init();
		
		connector.setHandler( new SessionHandler() );
	}
	
	private void init()
	{
		logger.info( "Configuring client..." );
		
		port = 49483;
		//serverAddress = "77.169.237.70"; //Local host for now
		serverAddress = "127.0.0.1";
	}
	
	public void start() throws IOException
	{
		logger.info( "Initializing client..." );
		logger.info( "Binding to " + serverAddress + " on port " + port + "..." );
		future = connector.connect( new InetSocketAddress( serverAddress, port ) );
		future.awaitUninterruptibly( 1000 ); //max 1 second
		
		if( !future.isConnected() )
		{
			return;
		}
	}
	
	public void stop()
	{
		connector.dispose();
	}
	
	public static Client getClient()
	{
		if( instance == null )
		{
			try
			{
				instance = new Client();
			}
			catch( Exception ex )
			{
				logger.error( "Can't start client...", ex );
			}
		}
		
		return instance;
	}
	
	public RPGSession getSession()
	{
		RPGSession sess = null;
		try
		{
			sess = new RPGSession( future.getSession() );

		}
		catch( Exception e )
		{
			System.err.println( "Could not get session..." );
			System.exit( 1 );
		}
		
		return sess;
	}
}
